package cn.merryyou.logback.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @Author: gongtao
 * @Date: Created in 2018/6/3 09:54
 * @Description: Druid 数据库连接池自动配置类，通过spring提供的条件化配置，如类路径下必须存在DruidDataSource类，且必须存在 druid.url 属性 此时配置才会生效
 *
 * Druid(德鲁伊) 的介绍：DRUID是阿里巴巴开源平台上一个数据库连接池实现，它结合了C3P0、DBCP、PROXOOL等DB池的优点，同时加入了日志监控，可以很好的监控DB池连接和SQL的执行情况，可以说是针对监控而生的DB连接池
 * Druid 的 github 地址是： https://github.com/alibaba/druid
 *
 * 项目中的 Druid 提供的监控地址是：http://host:port/druid/index.html
 *
 */

@Configuration
@EnableConfigurationProperties(DruidProperties.class)
@ConditionalOnClass(DruidDataSource.class)
@ConditionalOnProperty(prefix = "druid", name = "url")
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
public class DruidAutoConfiguration {

    // 注入数据库连接信息
    @Autowired
    private DruidProperties properties;

    /**
     * 生成 dataSource Bean 由 Spring 托管
     * @return
     */
    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        if (properties.getInitialSize() > 0) {
            dataSource.setInitialSize(properties.getInitialSize());
        }
        if (properties.getMinIdle() > 0) {
            dataSource.setMinIdle(properties.getMinIdle());
        }
        if (properties.getMaxActive() > 0) {
            dataSource.setMaxActive(properties.getMaxActive());
        }
        dataSource.setTestOnBorrow(properties.isTestOnBorrow());
        dataSource.setFilters(properties.getFilters()); // 添加 filter 用于监控，日志管理和防火墙配置
        try {
            dataSource.init();  // 初始化数据源
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return dataSource;
    }



}
